package com.handpay.zztong.hp;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HPLog;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.PurchaseStatus;
import com.handpay.zztong.hp.bean.UserAccount;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.ui.DialogFactory;
import com.handpay.zztong.hp.ui.MoneyEdit;

import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

public class PurchaseFundActivity extends ZZTongActivity {

	private TextView applyDate,purchaseDate,generateRevenueDate;
	private TextView todayPurchaseAmount,todaySuccessPurchaseAmount,AvailablePurchaseAmount;
	private CheckBox risk_cb;
	private Button purchaseApply;
	private String applyPurchaseAmount;
	private MoneyEdit purchaseAmount;
	private GfFoundIndex fundIndex = new GfFoundIndex();
	private String [] flowDesc;
	private Double availableRwdMoney;
	private UserAccount  users = null;
	private static final int ACTIVITY_APR_REQCODE = 101;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.applypurchase_fund);
		super.onCreate(savedInstanceState);
		getData();
		initView();
	}
	private void getData(){
		 
			if(getIntent() != null){
				  byte data[] = getIntent().getByteArrayExtra("data");
				  LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
//			 		String paymentProtocalUrl = (String)luaTable.rawget("paymentProtocalUrl");
//			 		HPLog.e("paymentProtocalUrl", "paymentProtocalUrl：" + paymentProtocalUrl);
			 		availableRwdMoney = (Double)luaTable.rawget("availableAmount");
			 	    LuaTable paymentWorkFlowDesc = (LuaTable) luaTable.rawget("paymentWorkFlowDesc");//arry<String>
			 	    flowDesc = fundIndex.getStringArrayFromTable(paymentWorkFlowDesc);
			 		LuaTable userActInfo = (LuaTable) luaTable.rawget("userActInfo");
		   	 		if(userActInfo != null){
		   	 		 users = GfFoundIndex.getUserAccount(userActInfo);	
		   	 		}
			 		HPLog.i("PurchaseFundActivity", "availableRwdMoney：" + availableRwdMoney);
			 		HPLog.i("PurchaseFundActivity", "paymentWorkFlowDesc：" + flowDesc);
			}
			
	}
	
	/**
	 * 控件初始化
	 */
	private void initView(){
//		findViewById(R.id.left_bar).setOnClickListener(this);
//		((TextView)findViewById(R.id.title)).setText(this.getString(R.string.purchaseFund));
		
		applyDate = (TextView)findViewById(R.id.applyDate);
		purchaseDate = (TextView)findViewById(R.id.purchaseDate);
		generateRevenueDate = (TextView)findViewById(R.id.generateRevenueDate);
		todayPurchaseAmount = (TextView)findViewById(R.id.todayPurchaseAmount);
		todaySuccessPurchaseAmount = (TextView)findViewById(R.id.todaySuccessPurchaseAmount);
		AvailablePurchaseAmount = (TextView)findViewById(R.id.currentAvailablePurchaseAmount);
		purchaseAmount = (MoneyEdit)findViewById(R.id.inputAmount);
		risk_cb = (CheckBox)findViewById(R.id.risk_cb); 
		((TextView)findViewById(R.id.risk_cb_tv)).getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
		findViewById(R.id.risk_cb_tv).setOnClickListener(this);
		purchaseApply = (Button)findViewById(R.id.purchaseApply_bt);
		purchaseApply.setOnClickListener(this);	
		setValue();
	}
	
	private void setValue(){
		applyDate.setText(flowDesc[0].replace("|", "\n"));
		purchaseDate.setText(flowDesc[1].replace("|", "\n"));
		generateRevenueDate.setText(flowDesc[2].replace("|", "\n"));
//		HPLog.i("PurchaseFundActivity", "amount：" + users.getTodayPaymentRequestAmount());
		todayPurchaseAmount.setText(users !=null?CommonUtils.formatMoneyDouble(Double.parseDouble(users.getTodayPaymentRequestAmount()+"")/100):"0.00");//今日申购申金额
		todaySuccessPurchaseAmount.setText(users != null?CommonUtils.formatMoneyDouble(Double.parseDouble(users.getTodayPaymentSuccAmount()+"")/100):"0.00"); //今日申购成功金额
		AvailablePurchaseAmount.setText(CommonUtils.formatMoneyDouble(Double.parseDouble(availableRwdMoney+"")/100));
		purchaseAmount.setText("");
	}
	/**
	 * 获取基金申购
	 */
	private void getzztGFPayment(Double amountApply){
		 Hashtable<String, String> params = new Hashtable<String, String>();
	    
	     params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
	     params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
	     params.put(BaseProtocolKey.PRODUCTCODE, "HLC");
	     String amountString = "" + Math.round(amountApply * 100);
	     params.put("amount", SecureManager.getInstance().des(amountString, 1, null));
	     this.doPost(this, Do_ZztGFPayment, params);
	}
	
	@Override
	protected boolean isShownTopBar() {		
		return true;
	}

	@Override
	protected boolean isShownTabs() {
		return false;
	}
	private boolean isInputAmount(){
		applyPurchaseAmount = purchaseAmount.getText().toString();
		if(TextUtils.isEmpty(applyPurchaseAmount)){
//			Toast.makeText(this, getResources().getString(R.string.please_inputPurchaseAmount), Toast.LENGTH_SHORT).show();
			 DialogFactory.showAlertDialog(this, getString(R.string.tip),
                     getString(R.string.please_inputPurchaseAmount), true);
			return false;
		}
		if(".".equals(applyPurchaseAmount)){
			DialogFactory.showAlertDialog(this, getString(R.string.tip),
                    getString(R.string.please_inputPurchaseAmount), true);
			return false;
		}
		double applyAmount = Double.parseDouble(applyPurchaseAmount);
		if( availableRwdMoney < applyAmount * 100){
			DialogFactory.showAlertDialog(this, getString(R.string.tip),
                    getString(R.string.please_inputSmallAmount_larger), true);
			return false;
		}
		if(0 >= applyAmount){
			DialogFactory.showAlertDialog(this, getString(R.string.tip),
					getString(R.string.please_inputPurchaseAmount), true);
			return false;
		}
		return true;
	}
	@Override
	public void onClick(View v) {
		super.onClick(v);
		if (v != null) {
            int i = v.getId();
            if (i == R.id.risk_cb_tv) {
            	
            	// https://www.handmart.cn/Financialmanagement/GFHLC/agreement.html
	        	Intent intent = new Intent(PurchaseFundActivity.this, ShowHtmlActivity.class);
				intent.putExtra(ShowHtmlActivity.ShowHtml_Title_Key,
						getResources().getString(R.string.GF_fund_risk_tip));
				intent.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key,
						getString(R.string.guangfa_fund_risk_url));
				PurchaseFundActivity.this.startActivity(intent);

            } else if (i == R.id.purchaseApply_bt) {
            	if(risk_cb.isChecked()){
            		 
                	if(isInputAmount()){
                		String applyAmount = "您本次申请申购金额为：" +  CommonUtils.formatMoneyDouble(Double.parseDouble(applyPurchaseAmount)) + "元";
                		showAlertDialog(this, getString(R.string.tip),applyAmount,true,"确认",new DialogInterface.OnClickListener() {
    					
                			@Override
                			public void onClick(DialogInterface dialog, int which) {
                				 double a=Double.parseDouble(applyPurchaseAmount);
                				HPLog.i("PurchaseFundActivity", "money:-------- "+ a);
                				
                				getzztGFPayment(a);
                				dialog.dismiss();
                			}
                		},"取消",new DialogInterface.OnClickListener() {
    					
                			@Override
                			public void onClick(DialogInterface dialog, int which) {
                				dialog.dismiss();
                			}
                		},null,null);
                	}	 	
                
            	} else {
            		DialogFactory.showAlertDialog(this, getString(R.string.tip),
                            getString(R.string.please_agreeRisk), true);
            	}
            }
		}
	}
	
	@Override
	public boolean netResponse(String action, Hashtable<String, Object> resp,
			boolean showAlert, OnClickListener on) {
		boolean result = super.netResponse(action, resp, showAlert, on);
		if (result == true) 
	    {		
	            this.setResult(Activity.RESULT_CANCELED);
	            this.closeProgressDialog();
	            return true;
	    }
		if(Do_ZztGFPayment.equals(action)){
			
			byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
   	 		LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
   	     	LuaTable purchase = (LuaTable) luaTable.rawget("purchaseStatus");
   	 		if(purchase !=null && purchase instanceof LuaTable){
   	 		HPLog.i("PurchaseFundActivity", "purchase：" + purchase);
   	 	    PurchaseStatus status = PurchaseStatus.generatePurchaseStatus(purchase);
	   	 	    if(status != null){
		   	 		Intent it = new Intent(this,ApplyPurchaseResult.class);
			 		it.putExtra("purchaseStatus", status);
			 		startActivityForResult(it, ACTIVITY_APR_REQCODE);
	   	 	    }else{
	   	 	    	System.out.println("status is null");
	   	 	    }
   	 		}else{
   	 			String responseCode = (String) luaTable.rawget("responseCode");
   	 			String errorMessage = (String) luaTable.rawget("errMessage");
   	 			System.out.println("fail"+responseCode+":"+errorMessage);
   	 			
   	 		}
   	 		
		}else if(Do_ZztGFPaymentInfo.equals(action)){
			byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);			
				if(null != data){
					  LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
				 		availableRwdMoney = (Double)luaTable.rawget("availableAmount");
				 	    LuaTable paymentWorkFlowDesc = (LuaTable) luaTable.rawget("paymentWorkFlowDesc");//arry<String>
				 	    flowDesc = fundIndex.getStringArrayFromTable(paymentWorkFlowDesc);
				 		LuaTable userActInfo = (LuaTable) luaTable.rawget("userActInfo");
			   	 		HPLog.i("PurchaseFundActivity", "userActInfo：" + userActInfo);
			   	 		if(userActInfo != null){
			   	 			users = GfFoundIndex.getUserAccount(userActInfo);
			   	 			setValue();
			   	 		}
				}
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == ACTIVITY_APR_REQCODE && resultCode == REQUEST_APPLYPR_CODE){
			Hashtable<String, String> params = new Hashtable<String, String>();
		     params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
		     params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
		     params.put(BaseProtocolKey.PRODUCTCODE, "HLC");
		     this.doPost(this, Do_ZztGFPaymentInfo, params);
		}
	}
	
//    @Override
//	public void onLeftBar(View v) {
//		setResult(REQUEST_APPLYPR_CODE_TIP);
//		goBack();
//	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK){
			setResult(REQUEST_APPLYPR_CODE_TIP);
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public ActionBar getActivityActionBar() {
		setResult(REQUEST_APPLYPR_CODE_TIP);
		return new ActionBar(this.getString(R.string.purchaseFund),true);
	}
}
